package com.xiaoma.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaomacdut
 * @date 2020年3月21日 下午10:37:12
 */
public class LockFairTest implements Runnable{
    
    // 创建公平锁
    private static ReentrantLock lock = new ReentrantLock();
    
    public void run(){
        while(true){
            lock.lock();
            try{
                System.out.println(Thread.currentThread().getName() + "获得锁");
            }finally{
                lock.unlock();
            }
        }
    }
    
    public static void main(String [] args){
        LockFairTest lft = new LockFairTest();
        Thread th1 = new Thread(lft);// 4个线程去获取锁，是非公平的。所以同一个线程可以多次获取锁
        Thread th2 = new Thread(lft);
        Thread th3 = new Thread(lft);
        Thread th4 = new Thread(lft);
        th1.start();
        th2.start();
        th3.start();
        th4.start();
    }
}
